package com.hy.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hy.common.Result;
import com.hy.entity.Weekly;
import com.hy.mapper.WeeklyMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class SysWeeklyServiceImpl implements SysWeeklyService {
    @Autowired
    private WeeklyMapper weeklyMapper;


    // 创建周刊
    @Override
    public Result<Weekly> createWeekly(Weekly weekly) {
        try {
            if (StringUtils.isEmpty(weekly.getWeeklyTitle()) || StringUtils.isEmpty(weekly.getFileUrl())) {
                return Result.error("周刊标题和文件URL不能为空");
            }

            weekly.setCreateTime(new Date());
            weekly.setUpdateTime(new Date());
            weekly.setDeleteFlag(0);
            if (weekly.getLikeNumbers() == null) {
                weekly.setLikeNumbers(0L);
            }

            // 调用 Mapper 的 insert 方法
            int rows = weeklyMapper.insert(weekly);
            return rows > 0 ? Result.success(weekly) : Result.error("创建失败");
        } catch (Exception e) {
            log.error("创建周刊异常", e);
            return Result.error("创建周刊异常：" + e.getMessage());
        }
    }

    // 获取所有周刊
    // 分页获取周刊信息
    // 服务层方法需要修改签名并添加查询条件
    @Override
    public Result<IPage<Weekly>> getWeeklyPage(Integer pageNum, Integer pageSize, String title, Integer minLikes, Integer maxLikes) {
        try {
            if (pageNum == null || pageNum <= 0) pageNum = 1;
            if (pageSize == null || pageSize <= 0) pageSize = 10;

            Page<Weekly> page = new Page<>(pageNum, pageSize);
            // 使用 LambdaQueryWrapper 并正确初始化
            LambdaQueryWrapper<Weekly> queryWrapper = new LambdaQueryWrapper<>();

            // 添加基本条件，使用方法引用替代字符串列名
            queryWrapper.eq(Weekly::getDeleteFlag, 0)
                    .orderByDesc(Weekly::getCreateTime);

            // 添加动态查询条件
            if (title != null && !title.isEmpty()) {
                queryWrapper.like(Weekly::getWeeklyTitle, title);
            }

            if (minLikes != null) {
                queryWrapper.ge(Weekly::getLikeNumbers, minLikes);
            }

            if (maxLikes != null) {
                queryWrapper.le(Weekly::getLikeNumbers, maxLikes);
            }

            IPage<Weekly> weeklyPage = weeklyMapper.selectPage(page, queryWrapper);
            return Result.success(weeklyPage);
        } catch (Exception e) {
            log.error("分页获取周刊列表异常", e);
            return Result.error("分页获取周刊列表异常：" + e.getMessage());
        }
    }

    // 根据ID获取周刊
    @Override
    public Result<Weekly> getWeeklyById(Long id) {
        try {
            if (id == null) {
                return Result.error("ID不能为空");
            }

            // 调用 Mapper 的 selectById 方法
            Weekly weekly = weeklyMapper.selectById(id);
            if (weekly == null || weekly.getDeleteFlag() == 1) {
                return Result.error("未找到该周刊");
            }

            return Result.success(weekly);
        } catch (Exception e) {
            log.error("获取周刊异常，ID={}", id, e);
            return Result.error("获取周刊异常：" + e.getMessage());
        }
    }

    // 更新周刊
    @Override
    public Result<Weekly> updateWeekly(Weekly weekly) {
        try {
            if (weekly.getId() == null) {
                return Result.error("ID不能为空");
            }

            // 检查周刊是否存在
            Weekly existWeekly = weeklyMapper.selectById(weekly.getId());
            if (existWeekly == null || existWeekly.getDeleteFlag() == 1) {
                return Result.error("未找到该周刊");
            }

            weekly.setUpdateTime(new Date());

            // 调用 Mapper 的 updateById 方法
            int rows = weeklyMapper.updateById(weekly);
            return rows > 0 ? Result.success(weeklyMapper.selectById(weekly.getId())) : Result.error("更新失败");
        } catch (Exception e) {
            log.error("更新周刊异常，ID={}", weekly.getId(), e);
            return Result.error("更新周刊异常：" + e.getMessage());
        }
    }

    // 根据ID删除周刊（逻辑删除）
    @Override
    public Result<String> deleteWeekly(Long id) {
        try {
            if (id == null) {
                return Result.error("ID不能为空");
            }

            // 检查周刊是否存在
            Weekly weekly = weeklyMapper.selectById(id);
            if (weekly == null || weekly.getDeleteFlag() == 1) {
                return Result.error("未找到该周刊");
            }

            // 逻辑删除：手动设置 deleteFlag 并更新
            weekly.setDeleteFlag(1);
            weekly.setUpdateTime(new Date());
            int rows = weeklyMapper.updateById(weekly);
            return rows > 0 ? Result.success("删除成功") : Result.error("删除失败");
        } catch (Exception e) {
            log.error("删除周刊异常，ID={}", id, e);
            return Result.error("删除周刊异常：" + e.getMessage());
        }
    }
}
